import Vue from 'vue'
import Router from 'vue-router'
import iView from 'iview'
import {navList} from './dynamicRouting'
import loadNav from './dynamicRouting.js'
import axios from "axios"//ajax
// import routes from './routers'
// import Vuex from 'vuex';

//全部请求接口
import apiUrl from '../api/api.js'
//表单提交数据格式化
import qs from 'qs'

import global from '../api/common.js'

Vue.use(Router)

Vue.prototype.axios = axios


const router = new Router({
  routes: navList
  // routes,
  // mode: 'history'
})



let getRouter;//用来获取后台拿到的路由
router.beforeEach((to, from, next) => {


  /*
  * 1.如果是登录
  *   没有token 登录
  *   有token  首页
  * 2.如果不是登录
  *   没有token 登录
  *   有token  跳过
  *
  * */
  const token = sessionStorage.getItem('loginData');
  /*
  * 1. 需要先判断  getRouter 执行菜单方法
  *
  *
  * */
  if(to.name == '_login'){
    if(!token){
      next() // 跳转
    }else{
      // 需要修改密码
      if(!!sessionStorage.getItem("agentPassword")){
        // next({name: '_login'}) // 跳转到登录页
        // 退出
        var data = {access_token: JSON.parse(sessionStorage.getItem('loginData')).access_token};
        data = qs.stringify(data);
        axios.post(apiUrl.logout, data, {headers: {'Content-Type': "application/x-www-form-urlencoded"}}).then().catch(err => {
          console.log('失败', err);
        })
        sessionStorage.clear();// 删除所有数据
        next({name: '_login'}) // 跳转到登录页

      }else{
        next({name: 'dept'}) // 跳转到登录页
      }
    }
  }else{
    if (to.name == "error_401" || to.name == "error_500" || to.name == "error_404" || to.name == 'mid') {//首页 401 500 404 全部放过
      if (!getRouter) { //不加这个判断，路由会陷入死循环
        loadNav.loadNav();
        getRouter = navList; //
        next({...to, replace: true})
      } else {
        next()
      }
    } else if (!token) {
      next({name: '_login'}) // 跳转到登录页
    } else {
      if (!getRouter) { //不加这个判断，路由会陷入死循环
        loadNav.loadNav();
        getRouter = navList; //
        next({...to, replace: true})
      } else {
        next()
      }
    }
  }
})


router.afterEach(to => {
  // setTitle(to, router.app)
  iView.LoadingBar.finish()
  window.scrollTo(0, 0)
})

export default router


